package org.iqiyi.util;
import lombok.extern.slf4j.Slf4j;
import org.iqiyi.util.excel.ExcelDeep;
import org.iqiyi.util.excel.ExcelField;
import org.iqiyi.util.excel.FieldReflectionUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/***
 * @ClassName: CommonUtil
 * @Description: 通用工具类
 * @Author: huqi
 * @Create_time: 11:20 2021-3-19
 */
@Slf4j
public class CommonUtil {
    /**
     * 隐藏构造
     */
    private CommonUtil() {
    }

    /**
     * 获取excel标题字节数组,会深入处理
     *
     * @param clzz 导出excel的字节对象  配合注解ExcelDeep+ExcelField使用
     * @return
     */
    public static List<String> getExcelHeaderList(Class<?> clzz) {
        List<String> headerList = new ArrayList<>();
        if (null != clzz) {
            //获取所有的字段
            Field[] fields = FieldReflectionUtil.getAllFields(clzz);
            Arrays.stream(fields).filter((Field field) -> !Modifier.isFinal(field.getModifiers())
                    && !Modifier.isStatic(field.getModifiers())).forEach(var -> {
                //判断是否有小对象
                if (var.isAnnotationPresent(ExcelDeep.class)) {
                    //渗透获取
                    try {
                        Object o = var.getType().newInstance();
                        Field[] typeFields = FieldReflectionUtil.getAllFields(o.getClass());
                        Arrays.stream(typeFields).filter((Field field) -> !Modifier.isFinal(field.getModifiers())
                                && !Modifier.isStatic(field.getModifiers())
                                && field.isAnnotationPresent(ExcelField.class)).forEach(var1 -> {
                            headerList.add(var1.getName());
                        });
                    } catch (InstantiationException | IllegalAccessException e) {
                        log.error("can not newInstance...:" + var.getType().getSimpleName(), e.getMessage(), e);
                    }
                }
                if (var.isAnnotationPresent(ExcelField.class)) {
                    headerList.add(var.getName());
                }
            });
        }
        return headerList;
    }

    /**
     * 按指定大小,分隔集合，将集合按规定个数分为n个部分
     *
     * @param list
     * @param len
     * @return
     */
    public static <T> List<List<T>> splitList(List<T> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return null;
        }
        //返回结果
        List<List<T>> result = new ArrayList<>();
        //传入集合长度
        int size = list.size();
        //分隔后的集合个数
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<T> subList = list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1)));
            result.add(subList);
        }
        return result;
    }



}
